package com.zlsy.secondtime.threadcoreknowledge.volatiledemo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author zhouliang
 * @date 2020/5/15 14:42
 * 用中断来修复线程中断的操作
 */
@Slf4j
public class WrongWayVolatileFixed {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue blockingQueue = new ArrayBlockingQueue<>(10);
        WrongWayVolatileFixed fixed = new WrongWayVolatileFixed();
        Producter producter = fixed.new Producter(blockingQueue);
        Thread thread = new Thread(producter);
        thread.start();
        Thread.sleep(2000);

        Consumer consumer = fixed.new Consumer(blockingQueue);
        while (consumer.isContinue()) {
            System.out.println(consumer.blockingQueue.take() + "被消费了！");
        }

        System.out.println("消费者不需要更多的数据了，请生产者停止生产！");

        thread.interrupt();
    }

    class Producter implements Runnable {

        private BlockingQueue blockingQueue;

        public Producter(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (num <= 100000 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        blockingQueue.put(num);
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                log.error("线程:{},被中断了！", Thread.currentThread().getName());
            } finally {
                System.out.println("生产者接收到信号，已停止..");
            }
        }
    }

    class Consumer {
        private BlockingQueue blockingQueue;

        public Consumer(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        private boolean isContinue() {
            return (Math.random() < 0.95);
        }
    }
}
